package _interview100;

import java.util.ArrayList;
import java.util.List;

/**
 * 39. 组合总和
 */
public class No39 {
    private int[] candidates;
    private List<List<Integer>> ans;
    private List<Integer> path;

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        this.candidates = candidates;
        ans = new ArrayList<>();
        path = new ArrayList<>();
        int n = candidates.length;
        dfs(n - 1, target);
        return ans;
    }

    private void dfs(int i, int c) {
        if (i < 0) {
            if (c == 0) ans.add(new ArrayList<>(path));
            return;
        }
        if (candidates[i] > c) dfs(i - 1, c);
        else {
            dfs(i - 1, c);
            path.add(candidates[i]);
            dfs(i, c - candidates[i]);
            path.remove(path.size() - 1);
        }
    }
}
